package io.wdb.config;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

public class DateConverter implements Converter<String, Date> {
	private Logger logger = LoggerFactory.getLogger(DateConverter.class);
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
	private SimpleDateFormat simpleDateFormatB = new SimpleDateFormat("yyyy-MM-dd HH");
	
	private SimpleDateFormat simpleDateFormatMi = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
	private SimpleDateFormat simpleDateFormatMiB = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	@Override
	public Date convert(String source) {
		logger.info("时间格式为：\t"+source);
		if ("".equals(source) || source == null) {
			return null;
		}
		try {
			if(source.length()>14) {
				if(source.contains(" ")&&source.contains(":")) {
					return simpleDateFormatMiB.parse(source);
				}
				if(source.contains("-")) {
					return simpleDateFormatMi.parse(source);
				}
			}else {
				if (source.contains(" ")&&source.contains("-")) {
					return simpleDateFormatB.parse(source);
				}
				if(source.contains("-")) {
					return simpleDateFormat.parse(source);
				}
			}
		} catch (ParseException e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}
		return null;
	}

}
